#!/usr/bin/env python

import sys, getopt, switch

def usage():
	print "usage: get_interfaces_status [-a address] [-h] [-p port]"
	print "\t-a or --address\t specify the IP address of the switch"
	print "\t(if not specified the command will be executed on every switchs"
	print "\t and on every ports ( -p --port ignored )"
	print "\t-p or --port\t specify the port of the switch"
	print "\t-h\t\t display this help"
	print



def split_switch_lines(str,nom_switch):
	elts = str.replace("\r", "").split(" ")
	splitted = []
	for elt in elts:
		if elt != "" and elt[0] != "-" and elt[0] != "\x08":
			splitted.append(elt)
	output = nom_switch + "\t"
	output += splitted[0][4:] + "\t"
	output += splitted[len(splitted)-5] + "\t"
	output += splitted[len(splitted)-4]
	return output

def run_command(list_switchs, command):
	for ip in list_switchs:
		#print "Connecting to " + ip + "..."
		tn = switch.connect(ip)
		if not tn:
			print "Error while connecting to " + ip
			continue
		name = switch.enable(tn)
		if not name:
			print "Error while connecting to " + ip
			continue
		#print "Connected on " + name
		#print "Running command \"" + command + "\"..."
		#print
		output = switch.run_command(tn, command)
		lines = output.split("\n")
		for line in lines:
			if "Fa0/" in line:
				print split_switch_lines(line,name)
			#if "Gi0/" in line:


	switch.quit(tn)
	# print

def main(argv):
	try:
		opts, args = getopt.getopt(argv[1:], "a:hp:", ["help", "address=", "port="])
	except getopt.GetoptError:
		usage()
		sys.exit(2)
	command = "show interfaces status"
	list_switchs = []
	for opt, arg in opts:
		if opt in ("-h", "--help"):
			usage()
			sys.exit()
		elif opt in ("-a", "--address"):
			list_switchs.append(arg)
		elif opt in ("-p", "--port"):
			port = arg
			command = "show interfaces FastEthernet 0/"+ port +" status"
	if list_switchs == []:
		list_switchs = switch.get_switch_list()
		command = "show interfaces status"	

	run_command(list_switchs,command)

if __name__ == "__main__":
	main(sys.argv)
